package com.config;

import com.bean.base.UserInfo;
import com.mapper.UserInfoMapper;
import com.mapper.repository.UserInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

@Component
public class SystemInit implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Value("${sys.admin.username}")
    private String username;

    @Value("${sys.admin.password}")
    private String password;


    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        System.out.println("系统初始化");//被调用了6次 ，触发了多个事件  默认是ApplicationEvent事件
        //ApplicationReadyEvent事件被触发了一次
        //判断admin是否存在
        int count=userInfoMapper.selectByUsername(username);
        if(count==0){
            UserInfo userInfo=new UserInfo();
            userInfo.setId(UUID.randomUUID().toString());
            userInfo.setUsername(username);
            userInfo.setPassword(password);
            userInfo.setCreatetime(LocalDateTime.now());
            userInfoRepository.save(userInfo);
        }
    }
}
